import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/utils/TaskUtils.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TaskTypeDetailViewModel extends ChangeNotifier {
  bool _isLoading = false;

  final List<Widget> _taskList = [];

  DateTime _selectedDate = DateTime.now();

  DateTime get selectedDate {
    return _selectedDate;
  }

  void changeSelectedDate(DateTime newDate) {
    _selectedDate = newDate;
    notifyListeners();
  }

  bool get isLoading {
    return _isLoading;
  }

  List<Widget>? get taskList {
    return _taskList;
  }

  Future<void> fetchTaskByDateAndKeyword(DateTime time, String keyword) async {
    notifyListeners();
    _isLoading = true;
    _taskList.clear();
    final prefs = await SharedPreferences.getInstance();
    String? id = prefs.getString("user-id");
    int? status = prefs.getInt("taskStatus");
    try {
      Map<String, dynamic> response =
          await HttpUtil().get("/task/taskByDate", data: {
        "id": id,
        "options": time,
        "keyword": keyword,
        "status": status,
      });
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      if (responseJsonEntity.code == 200) {
        if (responseJsonEntity.data != null) {
          Map<String, dynamic> map = responseJsonEntity.data;
          List<String> keys = map.keys.toList();
          for (String element in keys) {
            _taskList.add(TaskUtils.generateTaskList(element, map));
          }
        }
      }
    } catch (e) {
      print(e);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
